package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    /**
     * 注入Service 而不是mapper因为他没有批处理
     */

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private RoomInfoMapper roomInfoMapper;

    /**
     *
     * @param  apartmentItemVoPage
     * @param  queryVo
     * @return  分页查询公寓信息的方法
     *
     */
    @Override
    public Page<ApartmentItemVo> pageApartmentItemVo(Page<ApartmentItemVo> apartmentItemVoPage, ApartmentQueryVo queryVo) {

        return baseMapper.selectByPage(apartmentItemVoPage,queryVo);
    }

    /**
     * 保存或更新公寓信息的方法
     * 更新的逻辑是 删除以前所有的数据，然后直接根据id重新新增
     * @param apartmentSubmitVo
     */
    @Override
    public void saveOrUpdateApartmentInfo(ApartmentSubmitVo apartmentSubmitVo) {
        //获取公寓id 作为关联表中存储的公寓编号
        Long id = apartmentSubmitVo.getId();
        //获取id在前，有id 是更新，无id是保存
        if (id != null) {
            //更新操作
            //将当前公寓所关联的所有数据删除掉
            //1.删除公寓配套信息 只需要拿到apartment_id 根据id将所有是这个id的is_deleted=1(全删掉)
             LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
             apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
             apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

             //2. 删除公寓标签信息
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId, id));
            //3.删除公寓杂费信息
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,id));
            //4.删除公寓图片信息
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id));


        }

        //1.先保存公寓基本信息。虽然穿的是VO，但是VO是ApartmentInfo的子类，包含了基本信息
        saveOrUpdate(apartmentSubmitVo);


        //2.保存公寓配套信息id。 apartment_facility
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        //判断公寓配套的id集合是否为空
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            //创建公寓和配套关联的集合
            List<ApartmentFacility> apartmentFacilities = new ArrayList<>();
            //遍历facilityInfoIds集合，取出配套的id
            for (Long facilityInfoId : facilityInfoIds) {
                //System.out.println("facilityInfoId = " + facilityInfoId);
                // 创建ApartmentFacility对象
                ApartmentFacility apartmentFacility = ApartmentFacility.builder().
                        apartmentId(apartmentSubmitVo.getId())
                        .facilityId(facilityInfoId).build();

                apartmentFacilities.add(apartmentFacility);
            }
            //批量保存到关系表中
            apartmentFacilityService.saveBatch(apartmentFacilities);
        }

        //3.保存公寓标签信息 apartment_label
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();

        if (!CollectionUtils.isEmpty(labelIds)) {
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>();
            //遍历LabelList集合，取出配套的id
            for (Long labelId : labelIds) {

                //创建ApartmentLabel对象
                ApartmentLabel apartmentLabel = ApartmentLabel.builder().apartmentId(apartmentSubmitVo.getId()).labelId(labelId).build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        //4.保存公寓杂费信息 apartment_fee_value
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        // 判断feelValueIds 集合是否为空
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            List<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>();

            // 遍历feeValueIds 集合，取出配套的id
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().
                        apartmentId(apartmentSubmitVo.getId()).feeValueId(feeValueId).build();
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }


        //5.保存公寓图片信息  GrapVo是前端传过来的。需要自行构建GraphInfo实体类对象。 公寓的类型  公寓的id
        List<GraphVo> graphVoLists = apartmentSubmitVo.getGraphVoList();
        //判断公寓图片信息是否为空
        if (!CollectionUtils.isEmpty(graphVoLists)) {
            //创建公寓图片表的集合
            List<GraphInfo> graphInfoList = new ArrayList<>();

            //遍历 graphVoLists集合 取出配套的id
            for (GraphVo graphVo : graphVoLists) {
                //构建GraphInfo对象
                GraphInfo graphInfo = new GraphInfo();

                //设置图片名称
                graphInfo.setName(graphVo.getName());

                //设置图片所属类型为公寓
                graphInfo.setItemType(ItemType.APARTMENT);
                //设置图片所属的对象id  公寓或房间的id
                graphInfo.setItemId(id);
                // 设置图片的地址url
                graphInfo.setUrl(graphVo.getUrl());
                //添加graphInfo
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);

        }
    }

    @Override
    public ApartmentDetailVo getApartmentDetailVOById(Long id) {
        //1.根据id查询公寓信息
        ApartmentInfo apartmentInfo = this.getById(id);

        //2.根据公寓id和图片类型id查询图片信息,这里用mapper他不是一个独立的功能强哥说
       List<GraphVo> graphInfoList = graphInfoMapper.selectGraphVOByApartmentIdAndItemTypeId(id,ItemType.APARTMENT);
        //3.根据公寓id查询公寓的配套
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectFacilityInfoListByApartmentId(id);

        //4.根据公寓id查询公寓的标签
        List<LabelInfo> labelInfoList = labelInfoMapper.selectLabelInfoListByApartmentId(id);

        //5.根据公寓id查询公寓的杂费信息  此处查的是VO，要在Feevalue中显示对应的fee_key的name
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectFeeValueVOListByApartmentId(id);
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        //借助工具类，将公寓信息的属性复制给apartmentDetailVo
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);
       //设置图片
        apartmentDetailVo.setGraphVoList(graphInfoList);
        //设置配套
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);

        //设置标签
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        //设置杂费
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        return apartmentDetailVo;
    }

    /**
     * 根据id删除公寓信息, 因为公寓里有房间所有不能直接删除需要先查询房间信息表
     */
    @Override
    public void removeApartmentInfoById(Long id) {
        //1. 先查询公寓id 对应的房间数量
        long roomCount  = roomInfoMapper.selectCount(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId, id));

        if (roomCount > 0){
            //throw  new RuntimeException("该公寓下有房间不能删除");
            throw new LeaseException(ResultCodeEnum.APARTMENT_HAS_ROOM);
        }

        //调用Mybatis-plus 自带的方法，删除公寓信息
        this.removeById(id);

        //删除关联数据
        //将当前公寓所关联的所有数据删除掉
        //1.删除公寓配套信息 只需要拿到apartment_id 根据id将所有是这个id的is_deleted=1(全删掉)
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

        //2. 删除公寓标签信息
        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId, id));
        //3.删除公寓杂费信息
        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,id));
        //4.删除公寓图片信息
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id));
    }

}




